package com.joizhang.reactor.app;

import com.joizhang.reactor.framework.AbstractNioChannel;
import com.joizhang.reactor.framework.ChannelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;

/**
 * @author joizhang
 */
public class LoggingServerHandler implements ChannelHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggingServerHandler.class);

    private static final byte[] ACK = "Data logged successfully".getBytes();

    @Override
    public void handleChannelRead(AbstractNioChannel channel, Object readObject, SelectionKey key) {
        if (readObject instanceof ByteBuffer) {
            doLogging((ByteBuffer) readObject);
            sendReply(channel, key);
        }
    }

    private void sendReply(AbstractNioChannel channel, SelectionKey key) {
        ByteBuffer buffer = ByteBuffer.wrap(ACK);
        channel.write(buffer, key);
    }

    private static void doLogging(ByteBuffer data) {
        // assuming UTF-8 :(
        LOGGER.info(new String(data.array(), 0, data.limit()));
    }

}
